package com.qys.training.biz.auth.service.impl;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.qys.training.base.dto.PDFTextConfig;
import com.qys.training.base.enumerate.BizCodeEnum;
import com.qys.training.base.exception.QysException;
import com.qys.training.biz.auth.entity.Files;
import com.qys.training.biz.auth.entity.FilesExample;
import com.qys.training.biz.auth.mapper.FilesMapper;
import com.qys.training.biz.auth.service.ItextService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class ItextServiceImpl implements ItextService {

    private String fontPath = "static/fonts/";

    @Resource
    private FilesMapper filesMapper;

    @Override
    public int addText(Long id, PDFTextConfig config) throws IOException, DocumentException {
        FilesExample example = new FilesExample();
        FilesExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        List<Files> filesList = filesMapper.selectByExample(example);
        if (filesList.size() > 0) {
            Files fileInfo = filesList.get(0);
            String path = fileInfo.getFilePath() + File.separator + fileInfo.getFileName();
            PdfReader reader = new PdfReader(path);
            String tempName = UUID.randomUUID().toString() + ".pdf";
            FileOutputStream os = new FileOutputStream(fileInfo.getFilePath() + File.separator + tempName);
            PdfStamper stamper = new PdfStamper(reader, os);

            //默认参数 PDFTextConfig中设置了默认参数

            //添加文字水印
            PdfContentByte overContent = stamper.getOverContent(config.getPageNum());//操作页
            overContent.beginText();
//            BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            String desc = fontPath + config.getFont().getDescription();
            BaseFont font = BaseFont.createFont(desc, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//自定义字体
            overContent.setFontAndSize(font, config.getFontSize());//设置字体和字体大小
            overContent.setTextMatrix(30, 30);//设置字体矩阵
            overContent.showTextAligned(Element.ALIGN_LEFT, config.getText(), config.getX(), config.getY(), config.getRotation());//设置文字内容、坐标、旋转角度
            overContent.endText();

            stamper.close();
            os.close();
            reader.close();

            //文件修改后数据入库
            File file = new File(fileInfo.getFilePath() + File.separator + fileInfo.getFileName());
            boolean delete = file.delete();
            if (delete) {
                //删除成功
                File newFile = new File(fileInfo.getFilePath() + File.separator + fileInfo.getFileName());
                boolean b = new File(fileInfo.getFilePath() + File.separator + tempName).renameTo(newFile);
                Files files = new Files();
                try (FileInputStream fileInputStream = new FileInputStream(newFile)) {
                    //更新数据库数据
                    files.setFileMd5(DigestUtils.md5DigestAsHex(fileInputStream));
                    files.setUpdated(new Date());
                    files.setFileSize(String.valueOf(newFile.length()));
                    FilesExample.Criteria cri = example.createCriteria();
                    cri.andIdEqualTo(fileInfo.getId());
                    return filesMapper.updateByExampleSelective(files, example);
                }

            } else {
                //删除失败
                throw new QysException(BizCodeEnum.DELETE_ERROR.getCode(), BizCodeEnum.DELETE_ERROR.getDescription());
            }
        } else {
            //无此id文件
            throw new QysException(BizCodeEnum.ID_ERROR.getCode(), BizCodeEnum.ID_ERROR.getDescription());
        }

    }
}
